<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="50%"
    title="规格成本设置"
    :style="{ top: '20px' }"
    :closable="false"
  >
    <template #closeIcon>
      <a-icon type="close" @click.stop="submit" />
    </template>
    <a-form ref="form" :model="costDetailData">
      <vxe-grid
        ref="costDetailGrid"
        resizable
        show-overflow
        highlight-hover-row
        keep-source
        row-id="id"
        :expand-config="{ expandAll: true }"
        :columns="costDetailTableColumn"
        :toolbar-config="toolbarConfig"
        :data="costDetailData"
      >
        <!-- 工具栏 -->
        <template #toolbar_buttons>
          <a-space>
            <a-button type="primary" @click="openBatchAddProduct">新增</a-button>
          </a-space>
        </template>
        <!-- 单位 -->
        <template #unit_default="{ row, rowIndex }">
          <a-form-item
            :name="[rowIndex, 'unitId']"
            :rules="[{ required: true, message: '请选择单位' }]"
            no-style
          >
            <unit-selector v-model:value="row.unitId" />
          </a-form-item>
        </template>
        <!-- 消耗数量 列自定义内容 -->
        <template #consumeQuantity_default="{ row, rowIndex }">
          <a-form-item
            :name="[rowIndex, 'consumeQuantity']"
            :rules="[{ required: true, message: '请输入消耗数量' }]"
            no-style
          >
            <a-input-number
              v-model:value="row.consumeQuantity"
              :precision="2"
              :min="0"
              style="width: 100%"
            />
          </a-form-item>
        </template>
        <!-- 自定义操作栏 -->
        <template #action_default="{ rowIndex }">
          <a-space>
            <a-button type="link" size="small" @click="openBatchAddReplacementsProduct(rowIndex)">
              新增替换品
            </a-button>
            <a-button type="link" danger size="small" @click="deleteMainProduct(rowIndex)">
              删除
            </a-button>
          </a-space>
        </template>
        <!-- 替代品表格 -->
        <template #replacements_default="{ row, rowIndex }">
          <div style="padding: 0 10px 10px 10px">
            <vxe-grid
              ref="replacementsGrid"
              resizable
              show-overflow
              highlight-hover-row
              keep-source
              row-id="id"
              :columns="replacementsTableColumn"
              :toolbar-config="toolbarConfig"
              :data="row.replacements"
            >
              <!-- 工具栏 -->
              <template #toolbar_buttons> </template>
              <!-- 单位 -->
              <template #replacements_unit_default="replacementsData">
                <a-form-item
                  :name="[rowIndex, 'replacements', replacementsData.rowIndex, 'unitId']"
                  :rules="[{ required: true, message: '请输入消耗数量' }]"
                  no-style
                >
                  <unit-selector v-model:value="replacementsData.row.unitId" />
                </a-form-item>
              </template>
              <!-- 消耗数量 列自定义内容 -->
              <template #replacements_quantity_default="replacementsData">
                <a-form-item
                  :name="[rowIndex, 'replacements', replacementsData.rowIndex, 'consumeQuantity']"
                  :rules="[{ required: true, message: '请输入消耗数量' }]"
                  no-style
                >
                  <a-input-number
                    v-model:value="replacementsData.row.consumeQuantity"
                    :precision="2"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-item>
              </template>
              <!-- 自定义操作栏 -->
              <template #replacements_action_default="replacementsData">
                <a-space>
                  <a-button
                    type="link"
                    danger
                    size="small"
                    @click="
                      () => {
                        console.log(rowIndex);
                        console.log(replacementsData.rowIndex);
                        console.log(deleteReplacementsProduct);
                        deleteReplacementsProduct(rowIndex, replacementsData.rowIndex);
                      }
                    "
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </vxe-grid>
          </div>
        </template>
      </vxe-grid>
    </a-form>
    <template #footer>
      <div class="form-modal-footer">
        <a-space>
          <a-button type="primary" html-type="submit" @click="submit"> 确认 </a-button>
        </a-space>
      </div>
    </template>
  </a-modal>

  <batch-add-product
    ref="batchAddProductRef"
    :sc-id="'1234'"
    @confirm="addProduct"
    :disabled-row-ids="disabledRowIds"
  />

  <batch-add-product
    ref="batchAddReplacementsProductRef"
    :sc-id="'1234'"
    @confirm="addReplacementsProduct"
    :disabled-row-ids="disabledReplacementsRowIds"
  />
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue';
  import BatchAddProduct from '@/views/sc/sale/batch-add-product.vue';
  import UnitSelector from '@/components/Selector/src/UnitSelector.vue';

  const instance = getCurrentInstance();

  const emit = defineEmits(['confirm', 'close']);

  const visible = ref(false);

  const props = defineProps({
    productId: {
      type: String,
      required: true,
    },
    propertyId: {
      type: String,
      required: true,
    },
    itemId: {
      type: String,
      required: true,
    },
  });

  const costDetailData = defineModel('costDetailData', {
    type: Array,
    default: () => [],
  });

  const form = ref();

  const batchAddProductRef = ref();

  const batchAddReplacementsProductRef = ref();

  // 当前选中的主原料行索引
  const currentRowIndex = ref(null);

  // 禁用的主原料行ID列表
  const disabledRowIds = ref([]);

  // 禁用的替代品行ID列表
  const disabledReplacementsRowIds = ref([]);

  const costDetailTableColumn = ref([
    {
      title: '替代品',
      type: 'expand',
      width: 60,
      align: 'center',
      slots: { content: 'replacements_default' },
    },
    { field: 'productName', title: '原料名称', width: 160 },
    { field: 'categoryName', title: '原料分类', width: 120 },
    {
      field: 'unit',
      title: '消耗单位',
      width: 120,
      slots: { default: 'unit_default' },
    },
    {
      field: 'consumeQuantity',
      title: '消耗数量',
      minWidth: 100,
      slots: { default: 'consumeQuantity_default' },
    },
    { title: '操作', width: 150, fixed: 'right', slots: { default: 'action_default' } },
  ]);

  const replacementsTableColumn = ref([
    { field: 'productName', title: '原料名称', width: 160 },
    { field: 'categoryName', title: '原料分类', width: 120 },
    {
      field: 'unit',
      title: '消耗单位',
      width: 120,
      slots: { default: 'replacements_unit_default' },
    },
    {
      field: 'consumeQuantity',
      title: '消耗数量',
      minWidth: 100,
      slots: { default: 'replacements_quantity_default' },
    },
    { title: '操作', width: 80, fixed: 'right', slots: { default: 'replacements_action_default' } },
  ]);

  const toolbarConfig = ref({
    zoom: false,
    refresh: false,
    custom: false,
    // 自定义左侧工具栏
    slots: {
      buttons: 'toolbar_buttons',
    },
  });

  // 打开批量新增原料弹窗
  const openBatchAddProduct = () => {
    disabledRowIds.value = costDetailData.value.map((item) => item.productId);
    batchAddProductRef.value.openDialog();
  };

  // 批量新增原料
  const addProduct = (productList) => {
    productList.forEach((item) => {
      item.mainProductId = props.productId;
      item.propertyId = props.propertyId;
      item.itemId = props.itemId;
      item.type = 0;
      item.unitId = item.unit;
      item.replacements = [];
    });
    costDetailData.value.push(...productList);
  };

  // 打开批量新增替代品弹窗
  const openBatchAddReplacementsProduct = (rowIndex) => {
    currentRowIndex.value = rowIndex;
    disabledReplacementsRowIds.value = [];
    disabledReplacementsRowIds.value.push(...costDetailData.value.map((item) => item.productId));
    disabledReplacementsRowIds.value.push(
      ...costDetailData.value[rowIndex].replacements.map((item) => item.productId),
    );
    console.log(disabledReplacementsRowIds.value);
    batchAddReplacementsProductRef.value.openDialog();
  };

  // 批量新增替代品
  const addReplacementsProduct = (productList) => {
    productList.forEach((item) => {
      item.mainProductId = props.productId;
      item.propertyId = props.propertyId;
      item.itemId = props.itemId;
      item.sourceProductId = costDetailData.value[currentRowIndex.value].productId;
      item.unitId = item.unit;
      item.type = 1;
    });
    costDetailData.value[currentRowIndex.value].replacements.push(...productList);
  };

  // 删除主原料
  const deleteMainProduct = (rowIndex) => {
    costDetailData.value.splice(rowIndex, 1);
  };

  // 删除替代品
  const deleteReplacementsProduct = (rowIndex, replacementsRowIndex) => {
    costDetailData.value[rowIndex].replacements.splice(replacementsRowIndex, 1);
  };

  // 打开弹窗
  const openDialog = () => {
    visible.value = true;
  };

  // 关闭对话框
  const closeDialog = () => {
    visible.value = false;
    emit('close');
  };

  // 数据提交
  const submit = () => {
    form.value.validate().then((valid) => {
      if (valid) {
        emit('confirm', costDetailData.value);
        closeDialog();
      }
    });
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
